package com.xuan.dao;
import com.xuan.model.User;
import com.xuan.utils.MD5Utils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;

public class UserDao extends BaseDao{
    public boolean add(User user){
        try {
            String sql="INSERT INTO manager ( id,name, mob, password)\n" +
                    "VALUES\n" +
                    "  ((select nvl(max(id),0) from manager)+1,?,?,?)";
            return queryRunner.execute(sql,
                    user.getName(),
                    user.getMob(),
                    MD5Utils.stringToMD5(user.getPassword(),user.getMob())
            )==1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean delete(int id){
        try {
            String sql="DELETE\n" +
                    " FROM\n" +
                    "  manager\n" +
                    "WHERE id = ?";
            return queryRunner.execute(sql,id)==1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean updatePassword(User user){
        try {
            String sql="UPDATE\n" +
                    "  manager\n" +
                    " SET\n" +
                    "  password = ? \n" +
                    " WHERE mob = ?";
            return queryRunner.execute(sql,
                    MD5Utils.stringToMD5(user.getPassword(),user.getMob()),
                    user.getMob()
            )==1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public User get(int id){
        try {
            String sql="SELECT  id,name,mob FROM manager "
                    + " where id = ?";
            return queryRunner.query(sql, new BeanHandler<>(User.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public User login(String mob,String password){
        try {
            String sql="SELECT  id,name,mob FROM manager "
                    + " where mob = ? and password = ?";
            return queryRunner.query(sql, new BeanHandler<>(User.class),mob,
                    MD5Utils.stringToMD5(password,mob));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<User> getAll(){
        try {
            String sql="SELECT  id,NAME,mob FROM manager "
                    + " order by id";
            return queryRunner.query(sql, new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
